import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import { isTokenExpired } from '../utils/tokenUtils'
import Login from '../views/Login.vue'
import Layout from '../views/Layout.vue'
import Dashboard from '../views/Dashboard.vue'
import UserManagement from '../views/UserManagement.vue'
import RoleManagement from '../views/RoleManagement.vue'
import MenuManagement from '../views/MenuManagement.vue'
import PermissionManagement from '../views/PermissionManagement.vue'
import NoticeManagement from '../views/NoticeManagement.vue'
import NoticeView from '../views/NoticeView.vue'
import OperationLogManagement from '../views/OperationLogManagement.vue'
import SystemConfig from '../views/extension/SystemConfig.vue'

import Profile from '../views/Profile.vue'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/',
    component: Layout,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '仪表板'
        }
      },
      {
        path: '/system/user',
        name: 'UserManagement',
        component: UserManagement,
        meta: {
          title: '用户管理'
        }
      },
      {
        path: '/system/role',
        name: 'RoleManagement',
        component: RoleManagement,
        meta: {
          title: '角色管理'
        }
      },
      {
        path: '/system/menu',
        name: 'MenuManagement',
        component: MenuManagement,
        meta: {
          title: '菜单管理'
        }
      },
      {
        path: '/system/permission',
        name: 'PermissionManagement',
        component: PermissionManagement,
        meta: {
          title: '权限管理'
        }
      },
      {
        path: '/notice/management',
        name: 'NoticeManagement',
        component: NoticeManagement,
        meta: {
          title: '通知管理'
        }
      },
      {
        path: '/notice/view',
        name: 'NoticeView',
        component: NoticeView,
        meta: {
          title: '通知公告'
        }
      },
      {
        path: '/system/operation-log',
        name: 'OperationLogManagement',
        component: OperationLogManagement,
        meta: {
          title: '操作日志'
        }
      },
      {
        path: '/extension/system-config',
        name: 'SystemConfig',
        component: SystemConfig,
        meta: {
          title: '系统配置'
        }
      },

      {
        path: '/profile',
        name: 'Profile',
        component: Profile,
        meta: {
          title: '个人中心'
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const token = localStorage.getItem('token')

  // 检查token是否存在且有效
  const hasValidToken = token && !isTokenExpired(token)

  if (to.meta.requiresAuth) {
    if (hasValidToken) {
      // 如果有有效token但用户状态未初始化，先初始化
      if (!userStore.isLoggedIn) {
        try {
          userStore.initializeAuth()
        } catch (error) {
          console.error('用户状态初始化失败:', error)
          userStore.logout()
          next('/login')
          return
        }
      }
      next()
    } else {
      // token无效，清除状态并跳转登录页
      userStore.logout()
      next('/login')
    }
  } else {
    // 不需要认证的页面
    if (to.path === '/login') {
      if (hasValidToken && userStore.isLoggedIn) {
        // 如果已登录且访问登录页，重定向到首页
        // 添加防止无限重定向的检查
        if (from.path !== '/dashboard') {
          next('/dashboard')
        } else {
          next()
        }
      } else {
        // 确保清除可能存在的无效状态
        if (hasValidToken && !userStore.isLoggedIn) {
          userStore.logout()
        }
        next()
      }
    } else {
      next()
    }
  }
})

export default router 